<template>
  <div class="message-view">

    <div class="header">
      <h2>留言板</h2>
    </div>

    <div class="button-container">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">发表留言</el-button>
    </div>

    <el-card v-for="message in messageStore.messages" :key="message.id" class="message-card">
      <div class="message-header">
        <h3>{{ message.title }}</h3>
        <span>{{ message.studentName }} • {{ message.createTime }}</span>
      </div>
      <p class="message-content">{{ message.content }}</p>
      <div class="message-actions">
        <el-button type="text" @click="viewMessageDetails(message)">查看详情</el-button>
      </div>
    </el-card>

    <!-- 发表留言对话框 -->
    <el-dialog title="发表留言" v-model="createDialogVisible" width="40%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="createForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="createForm.content" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createMessage" :icon="Plus">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查看留言详情对话框 -->
    <el-dialog title="留言详情" v-model="viewDialogVisible" width="40%">
      <div class="message-detail">
        <h3>{{ currentMessage.title }}</h3>
        <p><strong>内容:</strong> {{ currentMessage.content }}</p>
        <p><strong>学生:</strong> {{ currentMessage.studentName }}</p>
        <p><strong>时间:</strong> {{ currentMessage.createTime }}</p>
        <h4>回复:</h4>
        <div v-if="!replies.length">
          <p class="no-replies">暂无回复</p>
        </div>
        <div v-else>
          <el-card class="message-card reply-card" v-for="(reply, index) in replies" :key="reply.id">
            <p><strong>教师:</strong> {{ reply.teacherName }}</p>
            <p><strong>内容:</strong> {{ reply.content }}</p>
            <p><strong>时间:</strong> {{ reply.createTime }}</p>
          </el-card>
        </div>
      </div>

      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>

    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { useMessageStore, Message, MessageCreateRequest, Reply } from '@/stores/api/message';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, ElNotification, type FormInstance, type FormRules } from 'element-plus';

const messageStore = useMessageStore();
const userStore = useUserStore();
const router = useRouter();

const createDialogVisible = ref(false);
const viewDialogVisible = ref(false);

const createForm = ref<MessageCreateRequest>({
  studentId: userStore.user.id,
  title: "",
  content: "",
});

const currentMessage = ref<Message>({ id: 0, title: "", content: "", studentId: 0, studentName: "", hasUnreadReply: false, createTime: "" });
const replies = ref<Reply[]>([]);

const formRules = ref<FormRules>({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur"}],
});

const createFormRef = ref<FormInstance>();

const showCreateDialog = () => {
  createForm.value = { studentId: userStore.user.id, title: "", content: '' };
  createDialogVisible.value = true;
};

const createMessage = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await messageStore.createMessage(createForm.value);
        createDialogVisible.value = false;
      } catch (error) {
        // ... 错误已在 store 中处理
      }
    }
  });
};

const viewMessageDetails = async (message: Message) => {
  currentMessage.value = message;
  try {
    replies.value = await messageStore.fetchReplies(message.id);
    if (message.hasUnreadReply) {
      await messageStore.markAsRead(message.id);
    }
    viewDialogVisible.value = true;
  } catch (error) {
    // 错误已在 store 中处理
  }
};

const checkNotifications = async () => {
  if (!userStore.user?.id) return;
  try {
    const notifications = await messageStore.fetchNotifications(userStore.user.id);
    notifications.forEach((notification: Message) => {
      ElNotification({
        title: '新回复提醒',
        message: `您的留言 "${notification.title}" 有新回复，请及时查看！`,
        type: 'info',
        onClick: () => {
          viewMessageDetails(notification);
        },
      });
    });
  } catch (error) {
    // 错误已在 store 中处理
  }
};

onMounted(() => {
  messageStore.fetchMessages();
  checkNotifications();
});
</script>

<style scoped>
.message-view {
  width: 80%;
  margin: 40px auto 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.button-container {
  margin-bottom: 20px;
}


.message-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-header h3 {
  font-size: 18px;
  margin: 0;
}

.message-content p {
  margin: 10px 0;
  color: #666;
}

.message-actions {
  text-align: right;
}

.message-detail h3 {
  margin-top: 0;
}

.message-detail p {
  margin: 10px 0;
}

.no-replies p {
  color: #999;
}

.reply-card {
    margin-top: 10px;
}

</style>